package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Server2 {
    private ServerSocket serverSocket;
    //每链接一个客户端，把该客户端对应的输出流存入集合，便于广播发送消息给所有客户端
    private List<PrintWriter> allOut = new ArrayList<>();

    public Server2(){
        try {
            System.out.println("正在启动服务器....");
            serverSocket = new ServerSocket(8090);
            System.out.println("服务器启动完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            while (true){
                System.out.println("等带客户端连接....");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端已经连接!");
                Runnable runnable = new ClientHandler(socket);
                Thread thread = new Thread(runnable);
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        public void run(){
            PrintWriter pw = null;
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );

                pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        socket.getOutputStream(),"UTF-8"
                                )
                        ),true
                );

                synchronized (allOut){
                    //连接上一个客户端就会通过socket创建一个输出流--用于给客户端写东西
                   allOut.add(pw);
                   sendMessage(host+"上线了，当前在线人数："+allOut.size());
                   System.out.println(host+"当前在线人数:"+allOut.size());
                }



                String message;
                while ((message = br.readLine()) != null){
                    System.out.println(host+"说："+message);
                    sendMessage(host+"说："+message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                synchronized (allOut){
                    //当一个客户端断开连接后，将对应的输出流从集合中移除，以免其他的线程将消息再次发送给该客户端。
                    Iterator<PrintWriter> it = allOut.iterator();
                    while (it.hasNext()){
                        PrintWriter pw1 = it.next();
                        if (pw == pw1){
                            it.remove();
                        }
                    }
                }
                sendMessage(host+"下线了，当前在线人数："+allOut.size());
                System.out.println(host+"下线了，当前在线人数："+allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void sendMessage(String message){
        synchronized (allOut){
           for (PrintWriter pw : allOut){
               pw.println(message);
           }
        }
    }

    public static void main(String[] args) {
        Server2 server2 = new Server2();
        server2.start();
    }

}
